package com.xyht.sca_s.student_manage_system.modules.teachAndStaffCheckInApplication.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.config.Configure;
import com.deepoove.poi.data.PictureRenderData;
import com.deepoove.poi.data.PictureType;
import com.deepoove.poi.data.Pictures;
import com.deepoove.poi.policy.PictureRenderPolicy;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.xyht.sca_s.student_manage_system.common.commonReturn.CommonCodeEnum;
import com.xyht.sca_s.student_manage_system.common.commonReturn.CommonResult;
import com.xyht.sca_s.student_manage_system.common.commonReturn.ExceptionCast;
import com.xyht.sca_s.student_manage_system.common.commonReturn.ResponseResult;
import com.xyht.sca_s.student_manage_system.common.util.ApiModelUtil;
import com.xyht.sca_s.student_manage_system.common.util.CacheUtil;
import com.xyht.sca_s.student_manage_system.common.util.TimeUtil;
import com.xyht.sca_s.student_manage_system.common.util.XWPFTUtil;
import com.xyht.sca_s.student_manage_system.modules.common.constant.FileSavePathConstant;
import com.xyht.sca_s.student_manage_system.modules.newTips.myEnum.AppTypeEnum;
import com.xyht.sca_s.student_manage_system.modules.newTips.myEnum.RangeTypeEnum;
import com.xyht.sca_s.student_manage_system.modules.newTips.myEnum.TipsTypeEnum;
import com.xyht.sca_s.student_manage_system.modules.newTips.util.NewTipsUtil;
import com.xyht.sca_s.student_manage_system.modules.teachAndStaffCheckInApplication.constant.CheckType;
import com.xyht.sca_s.student_manage_system.modules.teachAndStaffCheckInApplication.entity.SmsTeachAdministrativePromiseManage;
import com.xyht.sca_s.student_manage_system.modules.teachAndStaffCheckInApplication.entity.SmsTeachAdministrativeStaffCheckInApplication;
import com.xyht.sca_s.student_manage_system.modules.teachAndStaffCheckInApplication.entity.SmsTeachAdministrativeStaffCheckInApplicationDetail;
import com.xyht.sca_s.student_manage_system.modules.teachAndStaffCheckInApplication.entity.SmsTeachAdministrativeStaffCheckInApplicationProcess;
import com.xyht.sca_s.student_manage_system.modules.teachAndStaffCheckInApplication.entity.dto.*;
import com.xyht.sca_s.student_manage_system.modules.teachAndStaffCheckInApplication.entity.vo.*;
import com.xyht.sca_s.student_manage_system.modules.teachAndStaffCheckInApplication.mapper.*;
import com.xyht.sca_s.student_manage_system.modules.teachAndStaffCheckInApplication.service.SmsTeachAdministrativeStaffCheckInApplicationService;
import com.xyht.sca_s.student_manage_system.modules.user.entity.SmsRole;
import com.xyht.sca_s.student_manage_system.modules.user.entity.SmsUser;
import com.xyht.sca_s.student_manage_system.modules.user.mapper.SmsRoleMapper;
import com.xyht.sca_s.student_manage_system.modules.user.mapper.SmsUserMapper;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.*;
import java.util.concurrent.Future;
import java.util.stream.Collectors;

import static com.xyht.sca_s.student_manage_system.common.util.ParamCheckUtil.isNullOrEmpty;
import static com.xyht.sca_s.student_manage_system.modules.examinePaymentEquipment.constant.isExportProcessConstant.EXPORT_PROCESS_TRUE;
import static com.xyht.sca_s.student_manage_system.modules.examinePaymentEquipment.constant.paymentExamineStatusConstant.*;
import static com.xyht.sca_s.student_manage_system.modules.student.constant.StudentInfoCommonConstant.PER_SHEET_NUM;
import static com.xyht.sca_s.student_manage_system.modules.teachAndStaffCheckInApplication.constant.ApplicationState.TEACH_STAFF_REGISTER_PROCESS_WAITING;
import static com.xyht.sca_s.student_manage_system.modules.teachAndStaffCheckInApplication.constant.CheckType.PROCESS_ROLE_CHECK_TYPE;
import static com.xyht.sca_s.student_manage_system.modules.teachAndStaffCheckInApplication.constant.TeachAndStaffSex.TEACH_STAFF_BOY;
import static com.xyht.sca_s.student_manage_system.modules.teachAndStaffCheckInApplication.constant.teachAndStaffCheckInApplicationTypeConstant.*;
import static com.xyht.sca_s.student_manage_system.modules.teachAndStaffCheckInApplication.constant.teachStaffApplicationStatusConstant.*;
import static com.xyht.sca_s.student_manage_system.modules.visitor.contact.CheckType.PROCESS_PEOPLE_CHECK_TYPE;


/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author XYHT
 * @since 2023-05-05
 */
@Service
public class SmsTeachAdministrativeStaffCheckInApplicationServiceImpl extends ServiceImpl<SmsTeachAdministrativeStaffCheckInApplicationMapper, SmsTeachAdministrativeStaffCheckInApplication> implements SmsTeachAdministrativeStaffCheckInApplicationService {
    @Resource
    private FileSavePathConstant fileSavePathConstant;
    @Autowired
    SmsUserMapper smsUserMapper;
    @Autowired
    SmsTeachAdministrativeStaffCheckInApplicationMapper smsTeachAdministrativeStaffCheckInApplicationMapper;
    @Autowired
    SmsTeachAdministrativeStaffCheckInApplicationProcessMapper smsTeachAdministrativeStaffCheckInApplicationProcessMapper;
    @Autowired
    SmsTeachAdministrativeStaffCheckInApplicationDetailMapper smsTeachAdministrativeStaffCheckInApplicationDetailMapper;
    @Autowired
    SmsRoleMapper smsRoleMapper;
    @Autowired
    CacheUtil cacheUtil;
    @Autowired
    private NewTipsUtil newTipsUtil;
    @Autowired
    SmsTeachAdministrativeStaffCheckInApplicationMpjMapper smsTeachAdministrativeStaffCheckInApplicationMpjMapper;
    @Autowired
    ApiModelUtil apiModelUtil;
    @Autowired
    SmsTeachAdministrativePromiseManageMapper smsTeachAdministrativePromiseManageMapper;

    @Transactional
    @Override
    public ResponseResult smsTeachAdministrativeStaffCheckInApplicationAdd(
            SmsTeachAdministrativeStaffCheckInApplicationVO smsTeachAdministrativeStaffCheckInApplicationVO,
            String user_id) {
        List<SmsTeachAdministrativeStaffCheckInApplicationProcess> fillProcessList =
                smsTeachAdministrativeStaffCheckInApplicationProcessMapper.selectList(new QueryWrapper<SmsTeachAdministrativeStaffCheckInApplicationProcess>()
                        .lambda()
                        .eq(SmsTeachAdministrativeStaffCheckInApplicationProcess::getProcessIsApplicantEdit, true)
                        .eq(SmsTeachAdministrativeStaffCheckInApplicationProcess::getIsUse, true)
                        .orderByAsc(SmsTeachAdministrativeStaffCheckInApplicationProcess::getSort));
        if (fillProcessList != null && fillProcessList.size() > 0) {
            if (smsTeachAdministrativeStaffCheckInApplicationVO.getProcessList() == null ||
                    smsTeachAdministrativeStaffCheckInApplicationVO.getProcessList().size() < 1) {
                return CommonResult.failed(CommonCodeEnum.TEACH_STAFF_ALLOW_USER_NOT_SETTING);
            }
            //判断申请人是否将全部需要编辑流程填写
            List<SmsTeachAdministrativeStaffCheckInApplicationProcess> filterList = fillProcessList
                    .stream()
                    .filter(process -> {
                                List<String> result = smsTeachAdministrativeStaffCheckInApplicationVO.getProcessList()
                                        .stream()
                                        .filter(fillProcess -> fillProcess.getProcessId().equals(process.getId()))
                                        .map(SmsTeachAdministrativeStaffCheckInApplicationDetailVO::getId)
                                        .collect(Collectors.toList());
                                //匹配的去除  未匹配的留下
                                if (result.size() > 0) {
                                    return false;
                                } else {
                                    return true;
                                }
                            }
                    )
                    .collect(Collectors.toList());
            if (filterList.size() > 0) {
                return CommonResult.failed(CommonCodeEnum.TEACH_STAFF_ALLOW_PROCESS_NOT_FILL);
            }
        }

        if (isNullOrEmpty(smsTeachAdministrativeStaffCheckInApplicationVO.getSmsApplicantName()) ||
                isNullOrEmpty(smsTeachAdministrativeStaffCheckInApplicationVO.getSmsSex()) ||
                isNullOrEmpty(smsTeachAdministrativeStaffCheckInApplicationVO.getSmsNativePlace()) ||
                isNullOrEmpty(smsTeachAdministrativeStaffCheckInApplicationVO.getSmsDepartment()) ||
                isNullOrEmpty(smsTeachAdministrativeStaffCheckInApplicationVO.getSmsPosition()) ||
                isNullOrEmpty(smsTeachAdministrativeStaffCheckInApplicationVO.getSmsDateOfBirth()) ||
                isNullOrEmpty(smsTeachAdministrativeStaffCheckInApplicationVO.getSmsAddress()) ||
                isNullOrEmpty(smsTeachAdministrativeStaffCheckInApplicationVO.getSmsReasonForApplication()) ||
                isNullOrEmpty(smsTeachAdministrativeStaffCheckInApplicationVO.getSmsPhone()) ||
                isNullOrEmpty(smsTeachAdministrativeStaffCheckInApplicationVO.getSmsIdCard())) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        SmsUser smsUser = smsUserMapper.selectById(user_id);
        if (isNullOrEmpty(smsUser)) {
            return CommonResult.failed(CommonCodeEnum.DATA_NOT_FOUND);
        }
        SmsTeachAdministrativeStaffCheckInApplication smsTeachAdministrativeStaffCheckInApplication = new SmsTeachAdministrativeStaffCheckInApplication();
        smsTeachAdministrativeStaffCheckInApplication.setSmsAddress(smsTeachAdministrativeStaffCheckInApplicationVO.getSmsAddress());
        smsTeachAdministrativeStaffCheckInApplication.setUserId(user_id);
        smsTeachAdministrativeStaffCheckInApplication.setSmsApplicantName(smsTeachAdministrativeStaffCheckInApplicationVO.getSmsApplicantName());
        smsTeachAdministrativeStaffCheckInApplication.setSmsReasonForApplication(smsTeachAdministrativeStaffCheckInApplicationVO.getSmsReasonForApplication());
        smsTeachAdministrativeStaffCheckInApplication.setSmsSex(smsTeachAdministrativeStaffCheckInApplicationVO.getSmsSex());
        smsTeachAdministrativeStaffCheckInApplication.setSmsDateOfBirth(smsTeachAdministrativeStaffCheckInApplicationVO.getSmsDateOfBirth());
        smsTeachAdministrativeStaffCheckInApplication.setSmsIdCard(smsTeachAdministrativeStaffCheckInApplicationVO.getSmsIdCard());
        smsTeachAdministrativeStaffCheckInApplication.setSmsPhone(smsTeachAdministrativeStaffCheckInApplicationVO.getSmsPhone());
        smsTeachAdministrativeStaffCheckInApplication.setSmsPosition(smsTeachAdministrativeStaffCheckInApplicationVO.getSmsPosition());
        smsTeachAdministrativeStaffCheckInApplication.setSmsNativePlace(smsTeachAdministrativeStaffCheckInApplicationVO.getSmsNativePlace());
        smsTeachAdministrativeStaffCheckInApplication.setSmsDepartment(smsTeachAdministrativeStaffCheckInApplicationVO.getSmsDepartment());
        smsTeachAdministrativeStaffCheckInApplication.setSmsApplicationState(TEACH_STAFF_REGISTER_PROCESS_WAITING);
        smsTeachAdministrativeStaffCheckInApplicationMapper.insert(smsTeachAdministrativeStaffCheckInApplication);
        String application_id = smsTeachAdministrativeStaffCheckInApplication.getId();

        //创建审批流程
        List<SmsTeachAdministrativeStaffCheckInApplicationProcess> list = smsTeachAdministrativeStaffCheckInApplicationProcessMapper
                .selectList(new QueryWrapper<SmsTeachAdministrativeStaffCheckInApplicationProcess>()
                        .lambda().eq(SmsTeachAdministrativeStaffCheckInApplicationProcess::getIsUse,true)
                        .orderByAsc(SmsTeachAdministrativeStaffCheckInApplicationProcess::getSort));


        if (isNullOrEmpty(list) || list.size() <1) {
            ExceptionCast.cast(CommonResult.failed(CommonCodeEnum.TEACH_STAFF_PROCESS_NOT_SETTING));//无相关审批流程，请联系管理员
        }


        int sort = 1;
        for (SmsTeachAdministrativeStaffCheckInApplicationProcess process : list) {
            //判断管理员是否配置初始流程
            if (!process.getProcessIsApplicantEdit()) {
                if (isNullOrEmpty(process.getCheckId()) || isNullOrEmpty(process.getCheckType())) {
                    ExceptionCast.cast(CommonResult.failed(CommonCodeEnum.PAYMENT_PROCESS_NOT_SETTING));
                }
            }

            SmsTeachAdministrativeStaffCheckInApplicationDetail addDetail =
                    new SmsTeachAdministrativeStaffCheckInApplicationDetail();

            addDetail.setApplicationId(application_id);
            addDetail.setProcessId(process.getId());
            addDetail.setIsSign(process.getIsSign());
            addDetail.setIsStamp(process.getIsStamp());
            addDetail.setProcessName(process.getProcessName());
            addDetail.setDetailAllowStatus(EXAMINE_STATUS_WAIT_ALLOW);

            addDetail.setSort(sort++);

            //申请人可编辑流程
            if (process.getProcessIsApplicantEdit()) {
                List<SmsTeachAdministrativeStaffCheckInApplicationDetailVO> filterList = smsTeachAdministrativeStaffCheckInApplicationVO.getProcessList()
                        .stream()
                        .filter(fillProcess -> fillProcess.getProcessId().equals(process.getId()))
                        .collect(Collectors.toList());
                if (filterList.size() < 1) {
                    ExceptionCast.cast(CommonResult.failed(CommonCodeEnum.PAYMENT_ALLOW_PROCESS_NOT_FILL));
                }
                SmsTeachAdministrativeStaffCheckInApplicationDetailVO fillProcessReq = filterList.get(0);

                if (isNullOrEmpty(fillProcessReq.getCheckId())) {
                    ExceptionCast.cast(CommonResult.failed(CommonCodeEnum.INVALID_PARAM));
                }
                addDetail.setCheckId(fillProcessReq.getCheckId());
                addDetail.setCheckType(PROCESS_PEOPLE_CHECK_TYPE);
            } else {
                addDetail.setCheckId(process.getCheckId());
                addDetail.setCheckType(process.getCheckType());
            }
            smsTeachAdministrativeStaffCheckInApplicationDetailMapper.insert(addDetail);

        }



        //消息通知
        QueryWrapper<SmsTeachAdministrativeStaffCheckInApplicationDetail> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SmsTeachAdministrativeStaffCheckInApplicationDetail::getApplicationId, smsTeachAdministrativeStaffCheckInApplication.getId())
                             .eq(SmsTeachAdministrativeStaffCheckInApplicationDetail::getSort, 1)
                             .orderByAsc(SmsTeachAdministrativeStaffCheckInApplicationDetail::getSort);
        SmsTeachAdministrativeStaffCheckInApplicationDetail applicationDetail
                = smsTeachAdministrativeStaffCheckInApplicationDetailMapper.selectOne(queryWrapper);
        RangeTypeEnum rangeTypeEnum;
        if(applicationDetail.getProcessIsApplicationEdit().equals(1)){
            rangeTypeEnum = RangeTypeEnum.RANGE_TYPE_ENUM_PERSON;
        }
        else{
            if (applicationDetail.getCheckType() == PROCESS_ROLE_CHECK_TYPE) {
                rangeTypeEnum = RangeTypeEnum.RANGE_TYPE_ENUM_ROLE;
            } else {
                rangeTypeEnum = RangeTypeEnum.RANGE_TYPE_ENUM_PERSON;
            }
        }

        List<String> range_id_list = new ArrayList<>();
        range_id_list.add(applicationDetail.getCheckId());
        newTipsUtil.addNewTips(TipsTypeEnum.TIPS_TYPE_ENUM_ALLOW,
                user_id,
                rangeTypeEnum,
                range_id_list,
                AppTypeEnum.APP_TYPE_ENUM_CHECK_IN_APPLICATION,
                smsTeachAdministrativeStaffCheckInApplication.getId(),
                applicationDetail.getId()
        );
        return CommonResult.success();
    }

    //教职工查看申请
    @Override
    public ResponseResult selectSmsTeachAdministrativeStaffCheckInApplication(Integer application_state,
                                                                              Integer pageSize,
                                                                              Integer pageNum,
                                                                              String bg_date,
                                                                              String end_date,
                                                                              String user_id) {
        Date bgDate = null;
        Date endDate = null;
        if (!isNullOrEmpty(bg_date)) {
            bgDate = TimeUtil.StringtoDate(bg_date);
        }
        if (!isNullOrEmpty(end_date)) {
            endDate = TimeUtil.StringtoDate(end_date);

        }
        QueryWrapper<SmsTeachAdministrativeStaffCheckInApplication> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SmsTeachAdministrativeStaffCheckInApplication::getUserId, user_id);
        if (isNullOrEmpty(queryWrapper)) {
            return CommonResult.failed(CommonCodeEnum.DATA_NOT_FOUND);
        }
        if (bgDate != null) {
            queryWrapper.lambda().ge(SmsTeachAdministrativeStaffCheckInApplication::getCreateTime, bgDate);
        }
        if (endDate != null) {
            queryWrapper.lambda().le(SmsTeachAdministrativeStaffCheckInApplication::getCreateTime, endDate);
        }
        if (!isNullOrEmpty(application_state)) {
            queryWrapper.lambda().eq(SmsTeachAdministrativeStaffCheckInApplication::getSmsApplicationState, application_state);
        }
        queryWrapper.orderByDesc("create_time");
        Page<SmsTeachAdministrativeStaffCheckInApplication> page = new Page<>(pageNum, pageSize);
        smsTeachAdministrativeStaffCheckInApplicationMapper.selectPage(page, queryWrapper);
        List<SmsTeachAdministrativeStaffCheckInApplication> list = page.getRecords();
        List<SmsTeachAdministrativeStaffCheckInApplicationDTO> applicationDTOList = new ArrayList<>();
        if (!isNullOrEmpty(list) && list.size() > 0) {
            for (SmsTeachAdministrativeStaffCheckInApplication application : list) {
                QueryWrapper<SmsTeachAdministrativeStaffCheckInApplicationDetail> queryWrapper1 = new QueryWrapper<>();
                queryWrapper1.lambda().eq(SmsTeachAdministrativeStaffCheckInApplicationDetail::getApplicationId, application.getId());
                List<SmsTeachAdministrativeStaffCheckInApplicationDetail> list1
                        = smsTeachAdministrativeStaffCheckInApplicationDetailMapper.selectList(queryWrapper1);
                List<SmsTeachAdministrativeStaffCheckInApplicationDetailDTO> detailDTOList = new ArrayList<>();
                if (!isNullOrEmpty(list1) && list1.size() > 0) {
                    for (SmsTeachAdministrativeStaffCheckInApplicationDetail detail : list1) {
                        SmsTeachAdministrativeStaffCheckInApplicationDetailDTO smsTeachAdministrativeStaffCheckInApplicationDetailDTO
                                = new SmsTeachAdministrativeStaffCheckInApplicationDetailDTO();
                        smsTeachAdministrativeStaffCheckInApplicationDetailDTO.setApplicationState(detail.getDetailAllowStatus());
                        smsTeachAdministrativeStaffCheckInApplicationDetailDTO.setSort(detail.getSort());
                        if (detail.getDetailAllowStatus() != TEACH_STAFF_APPLICATION_STATUS_WAIT_ALLOW) {
                            SmsUser smsUser = smsUserMapper.selectById(detail.getApproverId());
                            smsTeachAdministrativeStaffCheckInApplicationDetailDTO.setAllowName(smsUser.getRealName());
                            smsTeachAdministrativeStaffCheckInApplicationDetailDTO.setPicHead(smsUser.getUserPic());
                        }
                        if (detail.getCheckType() == PROCESS_ROLE_CHECK_TYPE) {
                            SmsRole smsRole = smsRoleMapper.selectById(detail.getCheckId());
                            smsTeachAdministrativeStaffCheckInApplicationDetailDTO.setProcessRoleName(smsRole.getRoleName());
                        } else {
                            SmsUser smsUser = smsUserMapper.selectById(detail.getCheckId());
                            smsTeachAdministrativeStaffCheckInApplicationDetailDTO.setProcessRoleName(smsUser.getRealName());
                        }
                        detailDTOList.add(smsTeachAdministrativeStaffCheckInApplicationDetailDTO);
                    }
                }
                SmsTeachAdministrativeStaffCheckInApplicationDTO smsTeachAdministrativeStaffCheckInApplicationDTO
                        = new SmsTeachAdministrativeStaffCheckInApplicationDTO();
                BeanUtils.copyProperties(application, smsTeachAdministrativeStaffCheckInApplicationDTO);
                smsTeachAdministrativeStaffCheckInApplicationDTO.setDetailList(detailDTOList);
                applicationDTOList.add(smsTeachAdministrativeStaffCheckInApplicationDTO);
            }
        }
        int total = (int) page.getTotal();
        return CommonResult.success(applicationDTOList, total);
    }

    //教职工查看申请详情
    @Override
    public ResponseResult selectSmsTeachAdministrativeStaffCheckInApplicationById(String id, Integer pageSize, Integer pageNum) {
        QueryWrapper<SmsTeachAdministrativeStaffCheckInApplicationDetail> queryWrapper = new QueryWrapper<>();
        SmsTeachAdministrativeStaffCheckInApplication application
                = smsTeachAdministrativeStaffCheckInApplicationMapper.selectById(id);
        if (isNullOrEmpty(application)) {
            return CommonResult.failed(CommonCodeEnum.DATA_NOT_FOUND);
        }
        SmsTeachAdministrativeStaffCheckInApplicationDTO smsTeachAdministrativeStaffCheckInApplicationDTO
                = new SmsTeachAdministrativeStaffCheckInApplicationDTO();
        queryWrapper.lambda().eq(SmsTeachAdministrativeStaffCheckInApplicationDetail::getApplicationId, application.getId());
        List<SmsTeachAdministrativeStaffCheckInApplicationDetail> list = smsTeachAdministrativeStaffCheckInApplicationDetailMapper
                .selectList(queryWrapper);
        List<SmsTeachAdministrativeStaffCheckInApplicationDetailDTO> detailDTOList = new ArrayList<>();
        if (!isNullOrEmpty(list) && list.size() > 0) {
            for (SmsTeachAdministrativeStaffCheckInApplicationDetail detail : list) {
                SmsTeachAdministrativeStaffCheckInApplicationDetailDTO smsTeachAdministrativeStaffCheckInApplicationDetailDTO
                        = new SmsTeachAdministrativeStaffCheckInApplicationDetailDTO();
                smsTeachAdministrativeStaffCheckInApplicationDetailDTO.setApplicationState(detail.getDetailAllowStatus());
                smsTeachAdministrativeStaffCheckInApplicationDetailDTO.setSort(detail.getSort());
                if (detail.getDetailAllowStatus() != TEACH_STAFF_APPLICATION_STATUS_WAIT_ALLOW) {
                    SmsUser smsUser = smsUserMapper.selectById(detail.getApproverId());
                    smsTeachAdministrativeStaffCheckInApplicationDetailDTO.setAllowName(smsUser.getRealName());
                    smsTeachAdministrativeStaffCheckInApplicationDetailDTO.setPicHead(smsUser.getUserPic());
                }
                if (detail.getCheckType() == PROCESS_ROLE_CHECK_TYPE) {
                    SmsRole smsRole = smsRoleMapper.selectById(detail.getCheckId());
                    smsTeachAdministrativeStaffCheckInApplicationDetailDTO.setProcessRoleName(smsRole.getRoleName());
                }
                detailDTOList.add(smsTeachAdministrativeStaffCheckInApplicationDetailDTO);
            }
            BeanUtils.copyProperties(application, smsTeachAdministrativeStaffCheckInApplicationDTO);
            smsTeachAdministrativeStaffCheckInApplicationDTO.setDetailList(detailDTOList);
        }
        return null;
    }

    //审批人查看申请
    @Override
    public ResponseResult selectSmsTeachAdministrativeStaffCheckInApplicationByAllowUser(String teachStaffName,
                                                                                         String user_id,
                                                                                         Integer pageSize,
                                                                                         Integer pageNum,
                                                                                         String bg_date,
                                                                                         String end_date) {
        QueryWrapper<SmsTeachAdministrativeStaffCheckInApplication> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SmsTeachAdministrativeStaffCheckInApplication::getSmsApplicationState, TEACH_STAFF_APPLICATION_STATUS_WAIT_ALLOW);
        List<SmsTeachAdministrativeStaffCheckInApplication> list
                = smsTeachAdministrativeStaffCheckInApplicationMapper.selectList(queryWrapper);
        List<String> applicationIDList = list.stream().map(SmsTeachAdministrativeStaffCheckInApplication::getId).collect(Collectors.toList());
        List<String> roleIDList = cacheUtil.getRoleList(user_id);
        List<SmsTeachAdministrativeStaffCheckInApplicationDTO> applicationDTOList = new ArrayList<>();
        int total = 0;
        if (isNullOrEmpty(list) || list.size() == 0) {
            return CommonResult.success(applicationDTOList, total);
        }
        List<String> roleApplicationIDList = new ArrayList<>();
        List<String> personApplicationIDList = new ArrayList<>();
        if (!isNullOrEmpty(roleIDList) && roleIDList.size() > 0) {
            QueryWrapper<SmsTeachAdministrativeStaffCheckInApplicationDetail> roleQueryWrapper = new QueryWrapper<>();
            roleQueryWrapper.lambda()
                    .eq(SmsTeachAdministrativeStaffCheckInApplicationDetail::getDetailAllowStatus, TEACH_STAFF_APPLICATION_STATUS_WAIT_ALLOW)
                    .eq(SmsTeachAdministrativeStaffCheckInApplicationDetail::getCheckType, PROCESS_ROLE_CHECK_TYPE);
            if (!isNullOrEmpty(applicationIDList) && applicationIDList.size() > 0) {
                roleQueryWrapper.lambda().in(SmsTeachAdministrativeStaffCheckInApplicationDetail::getApplicationId, applicationDTOList);
            }
            roleQueryWrapper.lambda().in(SmsTeachAdministrativeStaffCheckInApplicationDetail::getCheckId, roleIDList);

            List<SmsTeachAdministrativeStaffCheckInApplicationDetail> applicationDetailList
                    = smsTeachAdministrativeStaffCheckInApplicationDetailMapper.selectList(roleQueryWrapper)
                    .stream()
                    .filter(detail -> {
                        Integer sort = detail.getSort();
                        if (sort == 1) {
                            return true;
                        }
                        QueryWrapper<SmsTeachAdministrativeStaffCheckInApplicationDetail> query = new QueryWrapper<>();
                        query.lambda()
                                .eq(SmsTeachAdministrativeStaffCheckInApplicationDetail::getApplicationId, detail.getApplicationId())
                                .eq(SmsTeachAdministrativeStaffCheckInApplicationDetail::getSort, detail.getSort() - 1);
                        SmsTeachAdministrativeStaffCheckInApplicationDetail smsTeachAdministrativeStaffCheckInApplicationDetail
                                = smsTeachAdministrativeStaffCheckInApplicationDetailMapper.selectOne(query);
                        if (smsTeachAdministrativeStaffCheckInApplicationDetail.getDetailAllowStatus() == TEACH_STAFF_APPLICATION_STATUS_WAIT_ALLOW) {
                            return false;
                        }
                        return true;
                    })
                    .collect(Collectors.toList());
            roleApplicationIDList = applicationDetailList.stream().map(SmsTeachAdministrativeStaffCheckInApplicationDetail::getApplicationId).distinct().collect(Collectors.toList());
        }
        QueryWrapper<SmsTeachAdministrativeStaffCheckInApplicationDetail> personQueryWrapper = new QueryWrapper<>();
        personQueryWrapper
//                .select("DISTINCT register_id")
                .lambda()
                .eq(SmsTeachAdministrativeStaffCheckInApplicationDetail::getDetailAllowStatus, TEACH_STAFF_APPLICATION_STATUS_WAIT_ALLOW)
                .eq(SmsTeachAdministrativeStaffCheckInApplicationDetail::getCheckType, CheckType.PROCESS_PEOPLE_CHECK_TYPE);

        if (!isNullOrEmpty(applicationIDList) && applicationIDList.size() > 0) {
            personQueryWrapper.lambda().in(SmsTeachAdministrativeStaffCheckInApplicationDetail::getApplicationId, applicationIDList);
        }
        personQueryWrapper.lambda().eq(SmsTeachAdministrativeStaffCheckInApplicationDetail::getCheckId, user_id);

        List<SmsTeachAdministrativeStaffCheckInApplicationDetail> personApplicationDetailList
                = smsTeachAdministrativeStaffCheckInApplicationDetailMapper.selectList(personQueryWrapper)
                .stream()
                .filter(detail -> {
                    Integer sort = detail.getSort();
                    if (sort == 1) {
                        return true;
                    }
                    QueryWrapper<SmsTeachAdministrativeStaffCheckInApplicationDetail> query = new QueryWrapper<>();
                    query.lambda()
                            .eq(SmsTeachAdministrativeStaffCheckInApplicationDetail::getApplicationId, detail.getApplicationId())
                            .eq(SmsTeachAdministrativeStaffCheckInApplicationDetail::getSort, detail.getSort() - 1);
                    SmsTeachAdministrativeStaffCheckInApplicationDetail smsTeachAdministrativeStaffCheckInApplicationDetail
                            = smsTeachAdministrativeStaffCheckInApplicationDetailMapper.selectOne(query);
                    if (smsTeachAdministrativeStaffCheckInApplicationDetail.getDetailAllowStatus() == TEACH_STAFF_APPLICATION_STATUS_WAIT_ALLOW) {
                        return false;
                    }
                    return true;
                })
                .collect(Collectors.toList());
        personApplicationIDList = personApplicationDetailList.stream().map(SmsTeachAdministrativeStaffCheckInApplicationDetail::getApplicationId).distinct().collect(Collectors.toList());

        List<String> result = new ArrayList<>();
        result.addAll(roleApplicationIDList);
        result.addAll(personApplicationIDList);
        List<String> resultList = result.stream().distinct().collect(Collectors.toList());
        if (isNullOrEmpty(resultList) || resultList.size() == 0) {
            return CommonResult.success(applicationDTOList, total);
        }
        Page<SmsTeachAdministrativeStaffCheckInApplication> page = new Page<>(pageNum, pageSize);
        QueryWrapper<SmsTeachAdministrativeStaffCheckInApplication> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.lambda().in(SmsTeachAdministrativeStaffCheckInApplication::getId, resultList)
                .orderByDesc(SmsTeachAdministrativeStaffCheckInApplication::getCreateTime);
        smsTeachAdministrativeStaffCheckInApplicationMapper.selectPage(page, queryWrapper1);
        total = (int) page.getTotal();
        List<SmsTeachAdministrativeStaffCheckInApplication> list1 = page.getRecords();
        if (!isNullOrEmpty(list1) && list1.size() > 0) {
            for (SmsTeachAdministrativeStaffCheckInApplication application : list1) {
                SmsTeachAdministrativeStaffCheckInApplicationDTO smsTeachAdministrativeStaffCheckInApplicationDTO
                        = new SmsTeachAdministrativeStaffCheckInApplicationDTO();
                BeanUtils.copyProperties(application, smsTeachAdministrativeStaffCheckInApplicationDTO);
                applicationDTOList.add(smsTeachAdministrativeStaffCheckInApplicationDTO);

            }
        }
        return CommonResult.success(applicationDTOList, total);
    }

    //审批人通过id查看申请详情
    @Override
    public ResponseResult selectByIdAllowUser(String id, Integer pageSize, Integer pageNum) {
        QueryWrapper<SmsTeachAdministrativeStaffCheckInApplicationDetail> queryWrapper = new QueryWrapper<>();
        SmsTeachAdministrativeStaffCheckInApplication application =
                smsTeachAdministrativeStaffCheckInApplicationMapper.selectById(id);
        if (isNullOrEmpty(application)) {
            return CommonResult.failed(CommonCodeEnum.DATA_NOT_FOUND);
        }
        SmsTeachAdministrativeStaffCheckInApplicationDTO smsTeachAdministrativeStaffCheckInApplicationDTO = new SmsTeachAdministrativeStaffCheckInApplicationDTO();
        queryWrapper.lambda().eq(SmsTeachAdministrativeStaffCheckInApplicationDetail::getApplicationId, application.getId());
        List<SmsTeachAdministrativeStaffCheckInApplicationDetail> list
                = smsTeachAdministrativeStaffCheckInApplicationDetailMapper.selectList(queryWrapper);
        List<SmsTeachAdministrativeStaffCheckInApplicationDetailDTO> detailDTOList = new ArrayList<>();
        if (!isNullOrEmpty(list) && list.size() > 0) {
            for (SmsTeachAdministrativeStaffCheckInApplicationDetail applicationDetail : list) {
                SmsTeachAdministrativeStaffCheckInApplicationDetailDTO smsTeachAdministrativeStaffCheckInApplicationDetailDTO
                        = new SmsTeachAdministrativeStaffCheckInApplicationDetailDTO();
                BeanUtils.copyProperties(applicationDetail, smsTeachAdministrativeStaffCheckInApplicationDetailDTO);
                smsTeachAdministrativeStaffCheckInApplicationDetailDTO.setApplicationState(applicationDetail.getDetailAllowStatus());
                smsTeachAdministrativeStaffCheckInApplicationDetailDTO.setSort(applicationDetail.getSort());
                //判断审核状态
                if (applicationDetail.getDetailAllowStatus() != TEACH_STAFF_APPLICATION_STATUS_WAIT_ALLOW) {
                    SmsUser smsUser = smsUserMapper.selectById(applicationDetail.getApproverId());
                    smsTeachAdministrativeStaffCheckInApplicationDetailDTO.setPicHead(smsUser.getUserPic());
                    smsTeachAdministrativeStaffCheckInApplicationDetailDTO.setAllowName(smsUser.getRealName());
                }
                //判断审核类型
                if (applicationDetail.getCheckType() == PROCESS_ROLE_CHECK_TYPE) {
                    SmsRole smsRole = smsRoleMapper.selectById(applicationDetail.getCheckId());
                    smsTeachAdministrativeStaffCheckInApplicationDetailDTO.setProcessRoleName(smsRole.getRoleName());
                }
                detailDTOList.add(smsTeachAdministrativeStaffCheckInApplicationDetailDTO);
            }
            BeanUtils.copyProperties(application, smsTeachAdministrativeStaffCheckInApplicationDTO);
            smsTeachAdministrativeStaffCheckInApplicationDTO.setDetailList(detailDTOList);
        }
        return CommonResult.success(smsTeachAdministrativeStaffCheckInApplicationDTO);
    }

    @Transactional
    //审批
    @Override
    public ResponseResult smsTeachAdministrativeStaffCheckInApplicationByAllow(SmsTeachStaffAllowVO smsTeachStaffAllowVO,

                                                                               String allow_person_id) {
        if(isNullOrEmpty(smsTeachStaffAllowVO.getApplicationId())||isNullOrEmpty(smsTeachStaffAllowVO.getDetailId())
        ||isNullOrEmpty(smsTeachStaffAllowVO.getAllowDetailStatus())){
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }

        //判断审批状态不是为通过状态
        if(smsTeachStaffAllowVO.getAllowDetailStatus()!=TEACH_STAFF_APPLICATION_STATUS_PASS
        &&smsTeachStaffAllowVO.getAllowDetailStatus()!=TEACH_STAFF_APPLICATION_STATUS_DENY){
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        SmsTeachAdministrativeStaffCheckInApplicationDetail applicationDetail = smsTeachAdministrativeStaffCheckInApplicationDetailMapper
                .selectOne(new QueryWrapper<SmsTeachAdministrativeStaffCheckInApplicationDetail>()
                .lambda()
                .eq(SmsTeachAdministrativeStaffCheckInApplicationDetail::getApplicationId,smsTeachStaffAllowVO.getApplicationId())
                .eq(SmsTeachAdministrativeStaffCheckInApplicationDetail::getId,smsTeachStaffAllowVO.getDetailId())
                .eq(SmsTeachAdministrativeStaffCheckInApplicationDetail::getDetailAllowStatus,TEACH_STAFF_APPLICATION_STATUS_WAIT_ALLOW));
        if(isNullOrEmpty(applicationDetail)){
            return CommonResult.failed(CommonCodeEnum.TEACH_STAFF_ALLOW_PROCESS_HAVE);
        }

        //判断该节点是否本人审批（防止调节点审批）
        if(applicationDetail.getCheckType() == PROCESS_PEOPLE_CHECK_TYPE){
            if(!applicationDetail.getCheckId().equals(allow_person_id)){
                return CommonResult.failed(CommonCodeEnum.TEACH_STAFF_ALLOW_FAIL);
            }
        }else {
            List<String> roleList = cacheUtil.getRoleList(allow_person_id);
            List<String> filterRoleList = roleList.stream().filter(role -> role.equals(applicationDetail.getCheckId())).collect(Collectors.toList());
            if (filterRoleList.size() < 1) {
                return CommonResult.failed(CommonCodeEnum.TEACH_STAFF_ALLOW_FAIL);
            }
            }
            if (!applicationDetail.getSort().equals(1)) {
                SmsTeachAdministrativeStaffCheckInApplicationDetail preDetail =
                        smsTeachAdministrativeStaffCheckInApplicationDetailMapper.selectOne(new QueryWrapper<SmsTeachAdministrativeStaffCheckInApplicationDetail>()
                                .lambda()
                                .eq(SmsTeachAdministrativeStaffCheckInApplicationDetail::getApplicationId, smsTeachStaffAllowVO.getApplicationId())
                                .eq(SmsTeachAdministrativeStaffCheckInApplicationDetail::getSort, applicationDetail.getSort() - 1));
                if (preDetail != null && isNullOrEmpty(preDetail.getId())) {
                    if (preDetail.getDetailAllowStatus() != TEACH_STAFF_APPLICATION_STATUS_PASS) {
                        return CommonResult.failed(CommonCodeEnum.TEACH_STAFF_ALLOW_FAIL);
                    }
                }
            }


            //判断是否后勤处分配后勤处填写分配信息
            if (applicationDetail.getProcessName().equals("后勤处")&&smsTeachStaffAllowVO.getAllowDetailStatus()==TEACH_STAFF_APPLICATION_STATUS_PASS) {

                    if (isNullOrEmpty(smsTeachStaffAllowVO.getSms_key_num()) ||
                            isNullOrEmpty(smsTeachStaffAllowVO.getSms_electricity_num()) ||
                            isNullOrEmpty(smsTeachStaffAllowVO.getSms_present_person()) ||
                            isNullOrEmpty(smsTeachStaffAllowVO.getSms_room_num()) ||
                            isNullOrEmpty(smsTeachStaffAllowVO.getSms_transferred_person()) ||
                            isNullOrEmpty(smsTeachStaffAllowVO.getSms_water_num())) {
                        return CommonResult.failed(CommonCodeEnum.TEACH_STAFF_PROCESS_FINANCE_NOT_FILL);
                    }


                SmsTeachAdministrativeStaffCheckInApplication updateApplication = new SmsTeachAdministrativeStaffCheckInApplication();
                updateApplication.setId(smsTeachStaffAllowVO.getApplicationId());
                updateApplication.setSmsKeyNum(smsTeachStaffAllowVO.getSms_key_num());
                updateApplication.setSmsElectricityNum(smsTeachStaffAllowVO.getSms_electricity_num());
                updateApplication.setSmsPresentPerson(smsTeachStaffAllowVO.getSms_present_person());
                updateApplication.setSmsRoomNum(smsTeachStaffAllowVO.getSms_room_num());
                updateApplication.setSmsTransferredPerson(smsTeachStaffAllowVO.getSms_transferred_person());
                updateApplication.setSmsWaterNum(smsTeachStaffAllowVO.getSms_water_num());
                smsTeachAdministrativeStaffCheckInApplicationMapper.updateById(updateApplication);
            }

            SmsTeachAdministrativeStaffCheckInApplicationDetail allowDetail1 = new SmsTeachAdministrativeStaffCheckInApplicationDetail();
            allowDetail1.setId(smsTeachStaffAllowVO.getDetailId());
            allowDetail1.setDetailAllowStatus(smsTeachStaffAllowVO.getAllowDetailStatus());
            allowDetail1.setApproverId(allow_person_id);
            if (!isNullOrEmpty(smsTeachStaffAllowVO.getDetailAllowOpinion())) {
                allowDetail1.setDetailAllowOption(smsTeachStaffAllowVO.getDetailAllowOpinion());
            }
            Date date = new Date();
            allowDetail1.setProcessTime(date);
            allowDetail1.setCheckId(allow_person_id);
            if (applicationDetail.getIsSign()) {
                if (isNullOrEmpty(smsTeachStaffAllowVO.getDetailAllowSign())) {
                    ExceptionCast.cast(CommonResult.failed(CommonCodeEnum.INVALID_PARAM));
                }
                allowDetail1.setDetailAllowSign(smsTeachStaffAllowVO.getDetailAllowSign());
            }
            if (applicationDetail.getIsStamp()) {
                if (isNullOrEmpty(smsTeachStaffAllowVO.getDetailAllowStamp())) {
                    ExceptionCast.cast(CommonResult.failed(CommonCodeEnum.INVALID_PARAM));
                }
                allowDetail1.setDetailAllowStamp(smsTeachStaffAllowVO.getDetailAllowStamp());
            }
            smsTeachAdministrativeStaffCheckInApplicationDetailMapper.updateById(allowDetail1);

            //判断是否重复审批

            //判断是否最后一个节点 是否驳回
            Boolean is_done = false;
            Integer detailCount = smsTeachAdministrativeStaffCheckInApplicationDetailMapper.selectCount(new QueryWrapper<SmsTeachAdministrativeStaffCheckInApplicationDetail>()
                    .lambda()
                    .eq(SmsTeachAdministrativeStaffCheckInApplicationDetail::getApplicationId, smsTeachStaffAllowVO.getApplicationId()));
            if (detailCount.equals(applicationDetail.getSort()) || smsTeachStaffAllowVO.getAllowDetailStatus() == TEACH_STAFF_APPLICATION_STATUS_DENY) {
                is_done = true;

                SmsTeachAdministrativeStaffCheckInApplication updateApplication = new SmsTeachAdministrativeStaffCheckInApplication();
                updateApplication.setId(smsTeachStaffAllowVO.getApplicationId());
                updateApplication.setProcessEndTime(date);
                updateApplication.setSmsApplicationState(smsTeachStaffAllowVO.getAllowDetailStatus());
                smsTeachAdministrativeStaffCheckInApplicationMapper.updateById(updateApplication);
            }

            //节点驳回 重置其余节点状态
            if (smsTeachStaffAllowVO.getAllowDetailStatus() == EXAMINE_STATUS_DENY) {
                SmsTeachAdministrativeStaffCheckInApplicationDetail updateDenyDetail =
                        new SmsTeachAdministrativeStaffCheckInApplicationDetail();
                updateDenyDetail.setDetailAllowStatus(EXAMINE_STATUS_DENY_FINISH);
                smsTeachAdministrativeStaffCheckInApplicationDetailMapper.update(updateDenyDetail, new QueryWrapper<SmsTeachAdministrativeStaffCheckInApplicationDetail>()
                        .lambda()
                        .eq(SmsTeachAdministrativeStaffCheckInApplicationDetail::getApplicationId, smsTeachStaffAllowVO.getApplicationId())
                        .eq(SmsTeachAdministrativeStaffCheckInApplicationDetail::getDetailAllowStatus, TEACH_STAFF_APPLICATION_STATUS_WAIT_ALLOW));
            }
//消息通知
        if (is_done) {
            boolean result_status = false;
            if (smsTeachStaffAllowVO.getAllowDetailStatus() == TEACH_STAFF_APPLICATION_STATUS_PASS) {
                result_status = true;
            }
            newTipsUtil.allowFinishTips(smsTeachStaffAllowVO.getApplicationId(), allow_person_id, result_status);
        } else {
            SmsTeachAdministrativeStaffCheckInApplicationDetail nextDetail =
                    smsTeachAdministrativeStaffCheckInApplicationDetailMapper.selectOne(new QueryWrapper<SmsTeachAdministrativeStaffCheckInApplicationDetail>()
                            .lambda()
                            .eq(SmsTeachAdministrativeStaffCheckInApplicationDetail::getApplicationId, smsTeachStaffAllowVO.getApplicationId())
                            .eq(SmsTeachAdministrativeStaffCheckInApplicationDetail::getSort, applicationDetail.getSort() + 1));
            RangeTypeEnum rangeTypeEnum;
            if(nextDetail.getProcessIsApplicationEdit().equals(1)){
                rangeTypeEnum = RangeTypeEnum.RANGE_TYPE_ENUM_PERSON;
            }
            else{
                if (nextDetail.getCheckType() == PROCESS_ROLE_CHECK_TYPE) {
                    rangeTypeEnum = RangeTypeEnum.RANGE_TYPE_ENUM_ROLE;
                }
                else{
                    rangeTypeEnum = RangeTypeEnum.RANGE_TYPE_ENUM_PERSON;
                }
            }

            List<String> rangeIDList = new ArrayList<>();
            rangeIDList.add(nextDetail.getCheckId());
            newTipsUtil.allowContinueTips(smsTeachStaffAllowVO.getApplicationId(),
                    allow_person_id,
                    rangeTypeEnum,
                    rangeIDList,
                    nextDetail.getId());
        }

            return CommonResult.success();


    }

  @Override
  public ResponseResult smsTeachAdministrativeStaffCheckInApplicationByAllowList(String user_id,Integer application_type, Integer pageNum, Integer pageSize,String search_str) {
        if (isNullOrEmpty(application_type)) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        List<SmsTeachAdministrativeStaffCheckInApplicationDTO> applicationDTOList = new ArrayList<>();
        int total = 0;
        //如果审批类型为已发起
        if (application_type == TEACH_AND_STAFF_TYPE_APPLY) {
            Page<SmsTeachAdministrativeStaffCheckInApplication> page = new Page<>(pageNum, pageSize);
            QueryWrapper<SmsTeachAdministrativeStaffCheckInApplication> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda()
                    .eq(SmsTeachAdministrativeStaffCheckInApplication::getUserId, user_id)
                    .orderByDesc(SmsTeachAdministrativeStaffCheckInApplication::getCreateTime);
            if(!isNullOrEmpty(search_str)){
                queryWrapper.lambda().and(q ->{
                   q.like(SmsTeachAdministrativeStaffCheckInApplication::getSmsDepartment,search_str)
                   .or()
                   .like(SmsTeachAdministrativeStaffCheckInApplication::getSmsIdCard,search_str);
                });
            }
            smsTeachAdministrativeStaffCheckInApplicationMapper.selectPage(page, queryWrapper);
            applicationDTOList = page.getRecords()
                    .stream()
                    .map(smsApplication -> {
                        SmsTeachAdministrativeStaffCheckInApplicationDTO applicationDTO =
                                new SmsTeachAdministrativeStaffCheckInApplicationDTO();
                        BeanUtils.copyProperties(smsApplication, applicationDTO);
                        applicationDTO.setApplicationId(smsApplication.getId());
                        //获取用户并设置用户信息
                        SmsUser smsUser = cacheUtil.getUserInfo(smsApplication.getUserId());
                        SmsTeachAdministrativeStaffUserDTO userDTO = new SmsTeachAdministrativeStaffUserDTO();
                        if (smsUser != null) {
                            BeanUtils.copyProperties(smsUser, userDTO);
                        }
                        applicationDTO.setApplyUserInfo(userDTO);

                        return applicationDTO;
                    })
                    .collect(Collectors.toList());
            total = (int) page.getTotal();
        }
        //如果审批类型为已办类型
        else if (application_type == TEACH_AND_STAFF_TYPE_ALLOWED) {

            Page<SmsTeachAdministrativeStaffCheckInapplicationMpjDTO> page = new Page<>(pageNum, pageSize);
            MPJLambdaWrapper<SmsTeachAdministrativeStaffCheckInApplicationDetail> mpjLambdaWrapper = new MPJLambdaWrapper<>();
            mpjLambdaWrapper.selectAll(SmsTeachAdministrativeStaffCheckInApplicationDetail.class)
                    .selectAll(SmsTeachAdministrativeStaffCheckInApplication.class)
                    .selectAs(SmsTeachAdministrativeStaffCheckInApplication::getCreateTime, "createTime")
                    .selectAs(SmsTeachAdministrativeStaffCheckInApplicationDetail::getId, "detailId")
                    .leftJoin(SmsTeachAdministrativeStaffCheckInApplication.class, SmsTeachAdministrativeStaffCheckInApplication::getId, SmsTeachAdministrativeStaffCheckInApplicationDetail::getApplicationId)
                    .eq(SmsTeachAdministrativeStaffCheckInApplicationDetail::getApproverId, user_id)
                    //.orderByDesc(SmsTeachAdministrativeStaffCheckInApplication::getCreateTime)
                    .orderByDesc(SmsTeachAdministrativeStaffCheckInApplicationDetail::getProcessTime)
            ;
            mpjLambdaWrapper.and(wrapper -> {
                wrapper.eq(SmsTeachAdministrativeStaffCheckInApplicationDetail::getDetailAllowStatus, TEACH_STAFF_APPLICATION_STATUS_PASS)
                        .or()
                        .eq(SmsTeachAdministrativeStaffCheckInApplicationDetail::getDetailAllowStatus, TEACH_STAFF_APPLICATION_STATUS_DENY);
            });
            if(!isNullOrEmpty(search_str)){
                List<String> userIds = smsUserMapper.selectList(new QueryWrapper<SmsUser>()
                        .lambda()
                        .like(SmsUser::getRealName, search_str))
                        .stream()
                        .map(SmsUser::getId).collect(Collectors.toList());

                mpjLambdaWrapper.and(q ->{
                    q.like(SmsTeachAdministrativeStaffCheckInApplication::getSmsDepartment,search_str)
                    .or()
                    .like(SmsTeachAdministrativeStaffCheckInApplication::getSmsIdCard,search_str);
                    if(userIds.size() > 0) {
                        q.or().in(SmsTeachAdministrativeStaffCheckInApplication::getUserId, userIds);
                    }
                });
            }
            smsTeachAdministrativeStaffCheckInApplicationMpjMapper.selectJoinPage(page, SmsTeachAdministrativeStaffCheckInapplicationMpjDTO.class, mpjLambdaWrapper);

            applicationDTOList = page.getRecords()
                    .stream()
                    .map(smsApplicationMPJDTO -> {
                        SmsTeachAdministrativeStaffCheckInApplicationDTO smsApplicationDTO = new SmsTeachAdministrativeStaffCheckInApplicationDTO();
                        BeanUtils.copyProperties(smsApplicationMPJDTO, smsApplicationDTO);
                        smsApplicationDTO.setCreateTime(smsApplicationMPJDTO.getCreateTime());

                        SmsUser applyUser = cacheUtil.getUserInfo(smsApplicationDTO.getUserId());
                        SmsTeachAdministrativeStaffUserDTO userDTO = new SmsTeachAdministrativeStaffUserDTO();
                        if (applyUser != null) {
                            BeanUtils.copyProperties(applyUser, userDTO);
                        }
                        smsApplicationDTO.setApplyUserInfo(userDTO);

                        SmsUser allowUser = cacheUtil.getUserInfo(smsApplicationDTO.getApproverId());
                        SmsTeachAdministrativeStaffUserDTO staffUserDTO = new SmsTeachAdministrativeStaffUserDTO();
                        if (allowUser != null) {
                            BeanUtils.copyProperties(allowUser, staffUserDTO);
                        }
                        smsApplicationDTO.setAllowUserInfo(staffUserDTO);

                        return smsApplicationDTO;
                    })
                    .collect(Collectors.toList());
            total = (int) page.getTotal();

        }

        //审批类型为待办
        else if (application_type == TEACH_AND_STAFF_TYPE_ALLOW_WAIT_ME) {
            List<String> roleList = cacheUtil.getRoleList(user_id);


            //获取所有待审批申请流程节点
            List<SmsTeachAdministrativeStaffCheckInApplicationDetail> detailList
                    = smsTeachAdministrativeStaffCheckInApplicationDetailMapper.selectList(new QueryWrapper<SmsTeachAdministrativeStaffCheckInApplicationDetail>()
                    .lambda()
                    .eq(SmsTeachAdministrativeStaffCheckInApplicationDetail::getDetailAllowStatus, TEACH_STAFF_APPLICATION_STATUS_WAIT_ALLOW));

            List<SmsTeachAdministrativeStaffCheckInApplicationDetail> filterDetailList = detailList.stream()
                    .filter(detail -> {
                        if(detail.getProcessIsApplicationEdit().equals(1)){
                            if (!detail.getCheckId().equals(user_id)) {
                                return false;
                            }
                        }
                        else{
                            if (detail.getCheckType() == PROCESS_PEOPLE_CHECK_TYPE) {
                                if (!detail.getCheckId().equals(user_id)) {
                                    return false;
                                }
                            } else {
                                List<String> filterRoleList = roleList.stream().filter(role -> role.equals(detail.getCheckId())).collect(Collectors.toList());
                                if (filterRoleList.size() < 1) {
                                    return false;
                                }
                            }

                        }

                        if (detail.getSort().equals(1)) {
                            return true;
                        }
                        //判断上一个流程节点是否完成
                        SmsTeachAdministrativeStaffCheckInApplicationDetail preDetail =
                                smsTeachAdministrativeStaffCheckInApplicationDetailMapper.selectOne(new QueryWrapper<SmsTeachAdministrativeStaffCheckInApplicationDetail>()
                                        .lambda()
                                        .eq(SmsTeachAdministrativeStaffCheckInApplicationDetail::getApplicationId, detail.getApplicationId())
                                        .eq(SmsTeachAdministrativeStaffCheckInApplicationDetail::getSort, detail.getSort() - 1)
                                        .eq(SmsTeachAdministrativeStaffCheckInApplicationDetail::getDetailAllowStatus, TEACH_STAFF_APPLICATION_STATUS_PASS));
                        if (preDetail == null || isNullOrEmpty(preDetail.getId())) {
                            return false;
                        }
                        return true;
                    })
                    .collect(Collectors.toList());
            if (filterDetailList.size() > 0) {
                List<String> detailIDList = filterDetailList.stream().map(SmsTeachAdministrativeStaffCheckInApplicationDetail::getId).collect(Collectors.toList());

                Page<SmsTeachAdministrativeStaffCheckInApplicationDetail> page = new Page<>(pageNum, pageSize);
                QueryWrapper<SmsTeachAdministrativeStaffCheckInApplicationDetail> queryWrapper = new QueryWrapper<>();
                queryWrapper.lambda()
                        .in(SmsTeachAdministrativeStaffCheckInApplicationDetail::getId, detailIDList)
                        .orderByDesc(SmsTeachAdministrativeStaffCheckInApplicationDetail::getCreateTime);
                smsTeachAdministrativeStaffCheckInApplicationDetailMapper.selectPage(page, queryWrapper);

                applicationDTOList = page.getRecords()
                        .stream()
                        .map(smsApplicationDetail -> {
                            SmsTeachAdministrativeStaffCheckInApplication smsTeachAdministrativeStaffCheckInApplication
                                    = smsTeachAdministrativeStaffCheckInApplicationMapper.selectById(smsApplicationDetail.getApplicationId());
                            SmsTeachAdministrativeStaffCheckInApplicationDTO smsTeachAdministrativeStaffCheckInApplicationDTO
                                    = new SmsTeachAdministrativeStaffCheckInApplicationDTO();
                            BeanUtils.copyProperties(smsTeachAdministrativeStaffCheckInApplication, smsTeachAdministrativeStaffCheckInApplicationDTO);
                            smsTeachAdministrativeStaffCheckInApplicationDTO.setApplicationId(smsApplicationDetail.getApplicationId());

                            SmsUser applyUser = cacheUtil.getUserInfo(smsTeachAdministrativeStaffCheckInApplicationDTO.getUserId());
                            SmsTeachAdministrativeStaffUserDTO smsTeachAdministrativeStaffUserDTO = new SmsTeachAdministrativeStaffUserDTO();
                            if (applyUser != null) {
                                BeanUtils.copyProperties(applyUser, smsTeachAdministrativeStaffUserDTO);
                            }
                            smsTeachAdministrativeStaffCheckInApplicationDTO.setApplyUserInfo(smsTeachAdministrativeStaffUserDTO);

                            smsTeachAdministrativeStaffCheckInApplicationDTO.setDetailId(smsApplicationDetail.getId());

                            return smsTeachAdministrativeStaffCheckInApplicationDTO;
                        })
                        .filter(q -> {
                            if(!isNullOrEmpty(search_str)){
                                List<String> userIds = smsUserMapper.selectList(new QueryWrapper<SmsUser>()
                                        .lambda()
                                        .like(SmsUser::getRealName, search_str))
                                        .stream()
                                        .map(SmsUser::getId).collect(Collectors.toList());
                                if(q.getSmsDepartment().contains(search_str)||q.getSmsIdCard().contains(search_str)){
                                    return true;
                                }
                                if(userIds.size()>0&&userIds.contains(q.getUserId())){
                                    return true;
                                }
                                return false;
//                                QueryWrapper<SmsTeachAdministrativeStaffCheckInApplication> queryWrapper1 = new QueryWrapper<>();
//                                queryWrapper1.lambda().eq(SmsTeachAdministrativeStaffCheckInApplication::getId,q.getApplicationId());
//                                queryWrapper1.lambda().and(w ->{
//                                    w.like(SmsTeachAdministrativeStaffCheckInApplication::getSmsDepartment,search_str)
//                                            .or()
//                                            .like(SmsTeachAdministrativeStaffCheckInApplication::getSmsIdCard,search_str);
//                                    if(userIds.size() > 0) {
//                                        w.or().in(SmsTeachAdministrativeStaffCheckInApplication::getUserId, userIds);
//                                    }

                            }

                            return true;
                        })
                        .collect(Collectors.toList());

            }
        }
      return CommonResult.success(applicationDTOList,applicationDTOList.size());
}


    @Override
    public ResponseResult getTeachAdministrativeStaffCheckInApplicationDetail(String application_id, String user_id) {
        if (isNullOrEmpty(application_id)) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        SmsTeachAdministrativeStaffCheckInApplication paymentExamine =
                smsTeachAdministrativeStaffCheckInApplicationMapper.selectById(application_id);
        if (paymentExamine == null || isNullOrEmpty(paymentExamine.getId())) {
            return CommonResult.failed(CommonCodeEnum.TEACH_STAFF_NOT_EXIST);
        }

        SmsTeachAdministrativeStaffCheckInApplicationDTO paymentExamineResp = new SmsTeachAdministrativeStaffCheckInApplicationDTO();
        BeanUtils.copyProperties(paymentExamine, paymentExamineResp);
        paymentExamineResp.setApplicationId(paymentExamine.getId());

        SmsUser smsUser = cacheUtil.getUserInfo(paymentExamine.getUserId());
        SmsTeachAdministrativeStaffUserDTO smsExamineUserResp = new SmsTeachAdministrativeStaffUserDTO();
        if (smsUser != null) {
            BeanUtils.copyProperties(smsUser, smsExamineUserResp);
        }
        paymentExamineResp.setApplyUserInfo(smsExamineUserResp);

        List<SmsTeachAdministrativeStaffCheckInApplicationDetailDTO> detailRespList =
                smsTeachAdministrativeStaffCheckInApplicationDetailMapper.selectList(new QueryWrapper<SmsTeachAdministrativeStaffCheckInApplicationDetail>()
                        .lambda()
                        .eq(SmsTeachAdministrativeStaffCheckInApplicationDetail::getApplicationId, application_id)
                        .orderByAsc(SmsTeachAdministrativeStaffCheckInApplicationDetail::getSort))
                        .stream()
                        .map(detail -> {
                            SmsTeachAdministrativeStaffCheckInApplicationDetailDTO detailResp = new SmsTeachAdministrativeStaffCheckInApplicationDetailDTO();
                            BeanUtils.copyProperties(detail, detailResp);
                            if(detailResp.getCheckType()==PROCESS_PEOPLE_CHECK_TYPE){
                                SmsUser smsUser1 = smsUserMapper.selectById(detailResp.getCheckId());
                                detailResp.setRealName(smsUser1.getRealName());
                                detailResp.setHeadPic(smsUser1.getUserPic());
                            }
                            else if(detailResp.getCheckType()==PROCESS_ROLE_CHECK_TYPE){
                                SmsRole smsRole = smsRoleMapper.selectById(detailResp.getCheckId());
                                detailResp.setRealName(smsRole.getRoleName());
                            }

                            if (!isNullOrEmpty(detailResp.getCheckId())&&detailResp.getDetailAllowStatus()!=TEACH_STAFF_APPLICATION_STATUS_WAIT_ALLOW) {
                                SmsUser userInfo = cacheUtil.getUserInfo(detailResp.getCheckId());
                                SmsTeachAdministrativeStaffUserDTO paymentExamineUserResp = new SmsTeachAdministrativeStaffUserDTO();
                                if (userInfo != null) {
                                    BeanUtils.copyProperties(userInfo, paymentExamineUserResp);

                                }
                                detailResp.setAllowUserInfo(paymentExamineUserResp);
                            }
                            return detailResp;
                        })
                        .collect(Collectors.toList());
        paymentExamineResp.setDetailList(detailRespList);
        return CommonResult.success(paymentExamineResp);

    }

    @Override
    public ResponseResult cancelSmsTeachAdministrativeStaffCheckInApplication(SmsTeachAdministrativeStaffCancelVO cancelVO, String user_id) {
        if(isNullOrEmpty(cancelVO.getApplicationId())){
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        //查看审批表是否存在并且是否为本人
        SmsTeachAdministrativeStaffCheckInApplication smsTeachAdministrativeStaffCheckInApplication =
                smsTeachAdministrativeStaffCheckInApplicationMapper.selectOne(new QueryWrapper<SmsTeachAdministrativeStaffCheckInApplication>()
                .lambda()
                .eq(SmsTeachAdministrativeStaffCheckInApplication::getId,cancelVO.getApplicationId())
                .eq(SmsTeachAdministrativeStaffCheckInApplication::getUserId,user_id));
        if(smsTeachAdministrativeStaffCheckInApplication==null||isNullOrEmpty(smsTeachAdministrativeStaffCheckInApplication.getId())){
            return CommonResult.failed(CommonCodeEnum.TEACH_STAFF_NOT_EXIST);
        }
        if(smsTeachAdministrativeStaffCheckInApplication.getSmsApplicationState()!=TEACH_STAFF_REGISTER_PROCESS_WAITING){
            return CommonResult.failed(CommonCodeEnum.TEACH_STAFF_CANCEL_FAIL_ALLOWED);
        }
        //判断是否审批中
//        List<SmsTeachAdministrativeStaffCheckInApplicationDetail> detailList =
//                smsTeachAdministrativeStaffCheckInApplicationDetailMapper.selectList(new QueryWrapper<SmsTeachAdministrativeStaffCheckInApplicationDetail>()
//                        .lambda()
//                        .eq(SmsTeachAdministrativeStaffCheckInApplicationDetail::getApplicationId, cancelVO.getApplicationId())
//                        .eq(SmsTeachAdministrativeStaffCheckInApplicationDetail::getDetailAllowStatus, TEACH_STAFF_APPLICATION_STATUS_PASS));
//        if (detailList != null && detailList.size() > 0) {
//            return CommonResult.failed(CommonCodeEnum.TEACH_STAFF_CANCEL_FAIL_ALLOWING);
//        }
        //撤回审批
        SmsTeachAdministrativeStaffCheckInApplication cancelApplication = new SmsTeachAdministrativeStaffCheckInApplication();
        cancelApplication.setId(cancelVO.getApplicationId());
        cancelApplication.setSmsApplicationState(TEACH_STAFF_APPLICATION_STATUS_CANCEL);
        cancelApplication.setProcessEndTime(new Date());
        smsTeachAdministrativeStaffCheckInApplicationMapper.updateById(cancelApplication);
        //修改节点状态
        SmsTeachAdministrativeStaffCheckInApplicationDetail cancelApplicationDetail = new SmsTeachAdministrativeStaffCheckInApplicationDetail();
        cancelApplicationDetail.setDetailAllowStatus(TEACH_STAFF_APPLICATION_STATUS_CANCEL);

        smsTeachAdministrativeStaffCheckInApplicationDetailMapper.update(cancelApplicationDetail, new QueryWrapper<SmsTeachAdministrativeStaffCheckInApplicationDetail>()
                .lambda()
                .eq(SmsTeachAdministrativeStaffCheckInApplicationDetail::getApplicationId, cancelVO.getApplicationId())
                .eq(SmsTeachAdministrativeStaffCheckInApplicationDetail::getDetailAllowStatus,TEACH_STAFF_APPLICATION_STATUS_WAIT_ALLOW));

        //消息通知
        newTipsUtil.cancelFinishTips(cancelVO.getApplicationId());

        return CommonResult.success();
    }

    @Override
    public ResponseResult getTeachAdministrativeStaffCheckInApplicationProcessList() {
        List<SmsTeachAdministrativeStaffCheckInApplicationProcessListDTO> list =
                smsTeachAdministrativeStaffCheckInApplicationProcessMapper.selectList(new QueryWrapper<SmsTeachAdministrativeStaffCheckInApplicationProcess>()
                .lambda()
                .eq(SmsTeachAdministrativeStaffCheckInApplicationProcess::getProcessIsApplicantEdit,true)
                        .eq(SmsTeachAdministrativeStaffCheckInApplicationProcess::getIsUse,true)
                .orderByAsc(SmsTeachAdministrativeStaffCheckInApplicationProcess::getSort))
                .stream()
                .map(process -> {
                 SmsTeachAdministrativeStaffCheckInApplicationProcessListDTO processListDTO =
                      new SmsTeachAdministrativeStaffCheckInApplicationProcessListDTO();
                      BeanUtils.copyProperties(process, processListDTO);
                      processListDTO.setProcessObjectId(process.getCheckId());
                      processListDTO.setProcessObjectType(process.getCheckType());
                        return processListDTO;
                        })
                        .collect(Collectors.toList());
        return CommonResult.success(list);
    }

    @Autowired
    XWPFTUtil xwpftUtil;
    @Override
    @Async
    public Future<ResponseResult> tableDownload(String apply_id, HttpServletResponse response) {
        SmsTeachAdministrativeStaffCheckInApplication checkInApplication = smsTeachAdministrativeStaffCheckInApplicationMapper.selectById(apply_id);
        if (checkInApplication == null || checkInApplication.getId() == null) {
            return new AsyncResult<>(CommonResult.failed(CommonCodeEnum.TEACH_STAFF_NOT_EXIST));
        }
//        if (checkInApplication.getSmsApplicationState() == WORK_STATUS_WAIT_ALLOW) {
//            return new AsyncResult<>(CommonResult.failed(CommonCodeEnum.WORK_APPLICATION_DOWNLOAD_FAIL));
//        }

        String OSName = System.getProperty("os.name");
        String filePath = OSName.toLowerCase().startsWith("win") ? fileSavePathConstant.getFILE_DOWNLOAD_PATH()
                : fileSavePathConstant.getFILE_DOWNLOAD_PATH_LINUX();

        String newFilePath = filePath + apply_id + ".docx";
        String pdfFilePath = filePath + apply_id + ".pdf";

        File pdfFile = new File(pdfFilePath);

      //  if (!pdfFile.exists()) {
            try {

                String smsSex = "";
                if (checkInApplication.getSmsSex() == TEACH_STAFF_BOY) {
                    smsSex = "男";
                } else {
                    smsSex = "女";
                }
                String signTime = TimeUtil.DateHanZiSimpleFormat(checkInApplication.getCreateTime());

                List<String> picTagList = new ArrayList<>();

                Map<String, Object> map = new HashMap<>();
                map.put("createTime", signTime);
                map.put("smsApplicantName", checkInApplication.getSmsApplicantName());
                map.put("smsSex", smsSex);
                map.put("smsNativePlace",checkInApplication.getSmsNativePlace());
                map.put("smsDepartment", checkInApplication.getSmsDepartment());
                map.put("smsDateOfBirth", checkInApplication.getSmsDateOfBirth());
                map.put("smsIdCard", checkInApplication.getSmsIdCard());
                map.put("smsPhone", checkInApplication.getSmsPhone());
                map.put("smsAddress", checkInApplication.getSmsAddress());
                map.put("smsReasonForApplication", checkInApplication.getSmsReasonForApplication());
                map.put("smsPosition", checkInApplication.getSmsPosition());
                map.put("smsRoomNum", checkInApplication.getSmsRoomNum());
                map.put("smsKeyNum", checkInApplication.getSmsKeyNum());
                map.put("smsElectricityNum", checkInApplication.getSmsElectricityNum());
                map.put("smsWaterNum", checkInApplication.getSmsWaterNum());
                map.put("smsTransfrredPerson", checkInApplication.getSmsTransferredPerson());
                map.put("smsPresentPerson", checkInApplication.getSmsPresentPerson());
                Wrapper<SmsTeachAdministrativePromiseManage> wrapper = new QueryWrapper<SmsTeachAdministrativePromiseManage>()
                        .orderByDesc("update_time");
                List<SmsTeachAdministrativePromiseManage> list = smsTeachAdministrativePromiseManageMapper.selectList(wrapper);

                map.put("promise",list.get(0).getPromise());



                //获取初始流程
                List<SmsTeachAdministrativeStaffCheckInApplicationProcess> processList = smsTeachAdministrativeStaffCheckInApplicationProcessMapper.selectList(new QueryWrapper<SmsTeachAdministrativeStaffCheckInApplicationProcess>()
                        .lambda()
                        .orderByAsc(SmsTeachAdministrativeStaffCheckInApplicationProcess::getSort));
                if (processList == null || processList.size() < 1) {
                    return new AsyncResult<>(CommonResult.failed(CommonCodeEnum.FAIL));
                }

                //获取申请流程
                List<SmsTeachAdministrativeStaffCheckInApplicationDetail> detailList = smsTeachAdministrativeStaffCheckInApplicationDetailMapper.selectList(new QueryWrapper<SmsTeachAdministrativeStaffCheckInApplicationDetail>()
                        .lambda()
                        .eq(SmsTeachAdministrativeStaffCheckInApplicationDetail::getApplicationId, apply_id));
                for (SmsTeachAdministrativeStaffCheckInApplicationProcess process : processList) {
                    List<SmsTeachAdministrativeStaffCheckInApplicationDetail> filterDetail = detailList
                            .stream()
                            .filter(detail -> detail.getProcessId().equals(process.getId()))
                            .collect(Collectors.toList());
                    if (filterDetail.size() > 0) {
                        SmsTeachAdministrativeStaffCheckInApplicationDetail detail = filterDetail.get(0);
                        if (detail.getDetailAllowStatus() == EXAMINE_STATUS_PASS) {
                            map.put("allowStatus" + process.getSort() + "", "同意");
                        } else if (detail.getDetailAllowStatus() == EXAMINE_STATUS_DENY) {
                            map.put("allowStatus" + process.getSort() + "", "拒绝");
                        } else {
                            map.put("allowStatus" + process.getSort() + "", "");
                        }

                        map.put("allowOption" + process.getSort() + "", detail.getDetailAllowOption());

                        //添加签名
                        if (isNullOrEmpty(detail.getDetailAllowSign())) {
                            map.put("allowSign" + process.getSort() + "", "");
                        } else {
                            String[] splitStr = detail.getDetailAllowSign().split("=");
                            String fileName = splitStr[splitStr.length - 1];

                            File file = new File(filePath + fileName);
                            if (file.exists()) {
                                InputStream inputStream = new FileInputStream(file);
                                PictureRenderData pictures = Pictures.ofStream(inputStream,
                                        PictureType.PNG).size(60, 60).create();

                                map.put("allowSign" + process.getSort() + "", pictures);
                                picTagList.add("allowSign" + process.getSort());
                            }

                        }

                        //添加印章
                        if (isNullOrEmpty(detail.getDetailAllowStamp())) {
                            map.put("allowStamp" + process.getSort() + "", "");
                        } else {
                            String[] splitStr = detail.getDetailAllowStamp().split("=");
                            String fileName = splitStr[splitStr.length - 1];

                            File file = new File(filePath + fileName);
                            if (file.exists()) {
                                InputStream inputStream = new FileInputStream(file);
                                PictureRenderData pictures = Pictures.ofStream(inputStream,
                                        PictureType.PNG).size(60, 60).create();

                                map.put("allowStamp" + process.getSort() + "", pictures);
                                picTagList.add("allowStamp" + process.getSort());
                            }

                        }

                        //审批时间
                        if (isNullOrEmpty(detail.getProcessTime())) {
                            map.put("detailAllowTime" + process.getSort() + "", "");
                        } else {
                            map.put("detailAllowTime" + process.getSort() + "", TimeUtil.DateHanZiSimpleFormat(detail.getProcessTime()));
                        }
                    } else {
                        map.put("allowStatus" + process.getSort() + "", "");
                        map.put("allowOption" + process.getSort() + "", "");
                        map.put("allowSign" + process.getSort() + "", "");
                        map.put("allowStamp" + process.getSort() + "", "");
                        map.put("detailAllowTime" + process.getSort() + "", "");
                    }
                }



                ClassPathResource resource = new ClassPathResource("applyTemplates/teachApplication.docx");
                InputStream is = resource.getInputStream();
                FileOutputStream outputStream = new FileOutputStream(newFilePath);

                XWPFTemplate template = XWPFTemplate.compile(is);

                //配置图片标签
                Configure config = template.getConfig();
                for (String tag : picTagList
                ) {
                    config.customPolicy(tag, new PictureRenderPolicy());
                }
                template.render(map);

                template.write(outputStream);

                is.close();
                outputStream.close();
                template.close();

                //word转pdf
                File destOri = new File(newFilePath);
                FileInputStream fileInputStream = new FileInputStream(destOri);
                FileOutputStream fileOutputStream = new FileOutputStream(pdfFilePath);

                Document document = new Document();
                document.loadFromStream(fileInputStream, FileFormat.Docx);
                //保存为PDF
                document.saveToFile(pdfFilePath, FileFormat.PDF);


                fileInputStream.close();
                fileOutputStream.close();
                document.close();

                log.debug("文件生成完成!");
            } catch (Exception e) {
                e.printStackTrace();
                return new AsyncResult<>(CommonResult.failed(CommonCodeEnum.FAIL));
            }
 //       }

        try {
            // 加载PDF文档
            PDDocument doc = PDDocument.load(pdfFile);
            doc.setAllSecurityToBeRemoved(true);
            // 创建水印
//            String watermark = "南充电影工业职业学院";
//            PDPageContentStream contentStream;
//
//            for (PDPage page : doc.getPages()) {
//                contentStream = new PDPageContentStream(doc, page, PDPageContentStream.AppendMode.APPEND, true, true);
//
//                //加载字体
//                ClassPathResource resource = new ClassPathResource("fonts/123.ttf");
//                InputStream is = resource.getInputStream();
//                PDFont font = PDType0Font.load(doc, is);
//
//
//                int startX = 0; // 起始位置 x 坐标
//                int startY = 0; // 起始位置 y 坐标
//                float angle = -45; // 角度
//                float interval = 220; // 间隔
//                float opacity = 0.3f; // 透明度
//                int colorR = 127; // 颜色 red 值
//                int colorG = 127; // 颜色 green 值
//                int colorB = 127; // 颜色 blue 值
//
//                //透明的
//                PDExtendedGraphicsState r0 = new PDExtendedGraphicsState();
//                r0.setNonStrokingAlphaConstant(opacity);
//                r0.setAlphaSourceFlag(true);
//                contentStream.setGraphicsStateParameters(r0);
//
//                //水印颜色
//                contentStream.setNonStrokingColor(colorR, colorG, colorB);
//                contentStream.beginText();
//                contentStream.setFont(font, 30f);
//
//                int x_times = (int) Math.ceil(page.getMediaBox().getWidth() / interval);
//                int y_times = (int) Math.ceil(page.getMediaBox().getHeight() / interval);
//                for (int x = startX; x <= x_times; x++) {
//                    for (int y = startY; y <= y_times; y++) {
//                        contentStream.setTextRotation(angle, (x * interval), (y * interval));
//                        contentStream.showText(watermark);
//                    }
//                }
//                contentStream.endText();
//                contentStream.restoreGraphicsState();
//                contentStream.close();
//                is.close();
//            }

//            response.reset();
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/vnd.pdf;charset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("教职工入住请示单预览.pdf", "utf-8"));
            response.setHeader("file-name", URLEncoder.encode("教职工入住请示单预览.pdf", "utf-8"));
            response.setHeader("file-type","download");
            response.setHeader("Access-Control-Expose-Headers", "file-type,file-name");
            //刷新缓冲
            response.flushBuffer();

            // 保存PDF文档
            doc.save(response.getOutputStream());
            doc.close();
        } catch (Exception e) {
            e.printStackTrace();
            return new AsyncResult<>(CommonResult.failed(CommonCodeEnum.FAIL));

        }
        return null;


        //        SmsTeachAdministrativeStaffCheckInApplication smsTeachAdministrativeStaffCheckInApplication
//                = smsTeachAdministrativeStaffCheckInApplicationMapper.selectById(apply_id);
//        if (smsTeachAdministrativeStaffCheckInApplication == null || smsTeachAdministrativeStaffCheckInApplication.getId() == null) {
//            return CommonResult.failed(CommonCodeEnum.TEACH_STAFF_NOT_EXIST);
//        }
//        if (smsTeachAdministrativeStaffCheckInApplication.getSmsApplicationState() == TEACH_STAFF_APPLICATION_STATUS_WAIT_ALLOW) {
//            return CommonResult.failed(CommonCodeEnum.TEACH_STAFF_DOWNLOAD_FAIL);
//        }
//
//        String OSName = System.getProperty("os.name");
//        String filePath = OSName.toLowerCase().startsWith("win") ? FILE_DOWNLOAD_PATH
//                : FILE_DOWNLOAD_PATH_LINUX;
//
//        String newFilePath = filePath + apply_id + ".docx";
//        String pdfFilePath = filePath + apply_id + ".pdf";
//
//        File pdfFile = new File(pdfFilePath);
//        if (!pdfFile.exists()) {
//            try {
//                String smsSex = "";
//                if (smsTeachAdministrativeStaffCheckInApplication.getSmsSex() == TEACH_STAFF_BOY) {
//                    smsSex = "女";
//                } else {
//                    smsSex = "男";
//                }
//                Map<String, Object> map = new HashMap<>();
//                map.put("${createTime}", TimeUtil.DateHanZiSimpleFormat(smsTeachAdministrativeStaffCheckInApplication.getCreateTime()));
//                map.put("${smsApplicantName}", smsTeachAdministrativeStaffCheckInApplication.getSmsApplicantName());
//                map.put("${smsSex}", smsSex);
//                map.put("${smsNativePlace}", smsTeachAdministrativeStaffCheckInApplication.getSmsNativePlace());
//                map.put("${smsDepartment}", smsTeachAdministrativeStaffCheckInApplication.getSmsDepartment());
//                map.put("${smsPosition}", smsTeachAdministrativeStaffCheckInApplication.getSmsPosition());
//                map.put("${smsDateOfBirth}", TimeUtil.DateHanZiSimpleFormat(smsTeachAdministrativeStaffCheckInApplication.getSmsDateOfBirth()));
//                map.put("${smsAddress}", smsTeachAdministrativeStaffCheckInApplication.getSmsAddress());
//                map.put("${smsReasonForApplication}", smsTeachAdministrativeStaffCheckInApplication.getSmsReasonForApplication());
//                map.put("${smsPhone}", smsTeachAdministrativeStaffCheckInApplication.getSmsPhone());
//                map.put("${smsIdCard}", smsTeachAdministrativeStaffCheckInApplication.getSmsIdCard());
//                map.put("${smsRoomNum}", smsTeachAdministrativeStaffCheckInApplication.getSmsRoomNum());
//                map.put("${smsKeyNum}", smsTeachAdministrativeStaffCheckInApplication.getSmsKeyNum());
//                map.put("${smsElectricityNum}", smsTeachAdministrativeStaffCheckInApplication.getSmsElectricityNum());
//                map.put("${smsWaterNum}", smsTeachAdministrativeStaffCheckInApplication.getSmsWaterNum());
//                map.put("${smsTransfrredPerson}", smsTeachAdministrativeStaffCheckInApplication.getSmsTransferredPerson());
//                map.put("${smsPresentPerson}", smsTeachAdministrativeStaffCheckInApplication.getSmsPresentPerson());
//                map.put("${smsApplicantName}", smsTeachAdministrativeStaffCheckInApplication.getSmsApplicantName());
//
//                //获取初始流程
//                List<SmsTeachAdministrativeStaffCheckInApplicationProcess> processList = smsTeachAdministrativeStaffCheckInApplicationProcessMapper.selectList(new QueryWrapper<SmsTeachAdministrativeStaffCheckInApplicationProcess>()
//                        .lambda()
//                        .orderByAsc(SmsTeachAdministrativeStaffCheckInApplicationProcess::getSort));
//                if (processList == null || processList.size() < 1) {
//                    return CommonResult.failed(CommonCodeEnum.FAIL);
//                }
//
//                //获取申请流程
//                List<SmsTeachAdministrativeStaffCheckInApplicationDetail> detailList = smsTeachAdministrativeStaffCheckInApplicationDetailMapper.selectList(new QueryWrapper<SmsTeachAdministrativeStaffCheckInApplicationDetail>()
//                        .lambda()
//                        .eq(SmsTeachAdministrativeStaffCheckInApplicationDetail::getApplicationId, apply_id));
//                for (SmsTeachAdministrativeStaffCheckInApplicationProcess process : processList) {
//                    List<SmsTeachAdministrativeStaffCheckInApplicationDetail> filterDetail = detailList
//                            .stream()
//                            .filter(detail -> detail.getProcessId().equals(process.getId()))
//                            .collect(Collectors.toList());
//                    if (filterDetail.size() > 0) {
//                        SmsTeachAdministrativeStaffCheckInApplicationDetail detail = filterDetail.get(0);
//                        if (detail.getDetailAllowStatus() == TEACH_STAFF_APPLICATION_STATUS_PASS) {
//                            map.put("${allowStatus" + process.getSort() + "}", "同意");
//                        } else if (detail.getDetailAllowStatus() == TEACH_STAFF_APPLICATION_STATUS_DENY) {
//                            map.put("${allowStatus" + process.getSort() + "}", "拒绝");
//                        } else {
//                            map.put("${allowStatus" + process.getSort() + "}", "");
//                        }
//
//                        map.put("${allowOption" + process.getSort() + "}", detail.getDetailAllowOption());
//
//
//                        //添加签名
//                        if (isNullOrEmpty(detail.getDetailAllowSign())) {
//                            map.put("${allowSign" + process.getSort() + "}", "");
//                        } else {
//                            String[] splitStr = detail.getDetailAllowSign().split("=");
//                            String fileName = splitStr[splitStr.length - 1];
//
//                            Map<String, Object> signMap = new HashMap<>();
//                            signMap.put("name", fileName);
//
//                            File file = new File(filePath + fileName);
//                            InputStream inputStream = new FileInputStream(file);
//                            signMap.put("picInputStream", inputStream);
//
//                            String[] typeSplit = fileName.split("u002E");
//                            String type = typeSplit[typeSplit.length - 1];
//                            signMap.put("type", type);
//
//                            map.put("${allowSign" + process.getSort() + "}", signMap);
//                        }
//
//                        //添加印章
//                        if (isNullOrEmpty(detail.getDetailAllowStamp())) {
//                            map.put("${allowStamp" + process.getSort() + "}", "");
//                        } else {
//                            String[] splitStr = detail.getDetailAllowStamp().split("=");
//                            String fileName = splitStr[splitStr.length - 1];
//
//                            Map<String, Object> stampMap = new HashMap<>();
//                            stampMap.put("name", fileName);
//
//                            File file = new File(filePath + fileName);
//                            InputStream inputStream = new FileInputStream(file);
//                            stampMap.put("picInputStream", inputStream);
//
//                            String[] typeSplit = fileName.split("u002E");
//                            String type = typeSplit[typeSplit.length - 1];
//                            stampMap.put("type", type);
//
//                            map.put("${allowStamp" + process.getSort() + "}", stampMap);
//                        }
//                    } else {
//                        map.put("${allowStatus" + process.getSort() + "}", "");
//                        map.put("${allowOption" + process.getSort() + "}", "");
//                        map.put("${allowSign" + process.getSort() + "}", "");
//                        map.put("${allowStamp" + process.getSort() + "}", "");
//                    }
//                }
//
//                InputStream is = null;
//
//                ClassPathResource resource = new ClassPathResource("applyTemplates/teachApplication.docx");
//                is = resource.getInputStream();
//                XWPFDocument doc = new XWPFDocument(is);
//
//                xwpftUtil.replaceInPara(doc, map);
//                xwpftUtil.replaceInTable(doc, map);
//
//
//                FileOutputStream outputStream = new FileOutputStream(newFilePath);
//
//                doc.write(outputStream);
//                is.close();
//
//                outputStream.close();
//                doc.close();
//
//                File destOri = new File(newFilePath);
//
//                FileInputStream fileInputStream = new FileInputStream(destOri);
//                XWPFDocument xwpfDocument = new XWPFDocument(fileInputStream);
//                PdfOptions pdfOptions = PdfOptions.create();
//                FileOutputStream fileOutputStream = new FileOutputStream(pdfFilePath);
//                PdfConverter.getInstance().convert(xwpfDocument, fileOutputStream, pdfOptions);
//
//
//                fileInputStream.close();
//                xwpfDocument.close();
//                fileOutputStream.close();
//
//                log.debug("文件生成完成!");
//            } catch (Exception e) {
//                e.printStackTrace();
//                return CommonResult.failed(CommonCodeEnum.FAIL);
//            }
//        }
//        try {
//            // 加载PDF文档
//            PDDocument doc = PDDocument.load(pdfFile);
//            doc.setAllSecurityToBeRemoved(true);
//            // 创建水印
//            String watermark = "南充电影学院";
//            PDPageContentStream contentStream;
//
//            for (PDPage page : doc.getPages()) {
//                contentStream = new PDPageContentStream(doc, page, PDPageContentStream.AppendMode.APPEND, true, true);
//
//                //加载字体
//                ClassPathResource resource = new ClassPathResource("fonts/123.ttf");
//                InputStream is = resource.getInputStream();
//                PDFont font = PDType0Font.load(doc, is);
//
//
//                int startX = 0; // 起始位置 x 坐标
//                int startY = 0; // 起始位置 y 坐标
//                float angle = -45; // 角度
//                float interval = 160; // 间隔
//                float opacity = 0.3f; // 透明度
//                int colorR = 127; // 颜色 red 值
//                int colorG = 127; // 颜色 green 值
//                int colorB = 127; // 颜色 blue 值
//
//                //透明的
//                PDExtendedGraphicsState r0 = new PDExtendedGraphicsState();
//                r0.setNonStrokingAlphaConstant(opacity);
//                r0.setAlphaSourceFlag(true);
//                contentStream.setGraphicsStateParameters(r0);
//
//                //水印颜色
//                contentStream.setNonStrokingColor(colorR, colorG, colorB);
//                contentStream.beginText();
////                contentStream.setFont(PDType1Font.HELVETICA, 30f);
//                contentStream.setFont(font, 30f);
////                page.getResources().add(font);
//                for (int x = startX; x < page.getMediaBox().getWidth(); x += interval) {
//                    for (int y = startY; y < page.getMediaBox().getHeight(); y += interval) {
//                        contentStream.setTextRotation(angle, x, y);
//                        contentStream.showText(watermark);
//                    }
//                }
//                contentStream.endText();
//                contentStream.restoreGraphicsState();
//                is.close();
//                contentStream.close();
//
//            }
//
////            response.reset();
//            response.setCharacterEncoding("utf-8");
//            response.setContentType("application/vnd.pdf;charset=utf-8");
//            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("教职工入住请示单预览.pdf", "utf-8"));
//
//            //刷新缓冲
//            response.flushBuffer();
//            // 保存PDF文档
//            OutputStream outputStream = response.getOutputStream();
//            doc.save(outputStream);
//            outputStream.close();
//            doc.close();
//
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//
//        return null;
    }

    @Override
    public ResponseResult selectAllApply(String apply_unit, Integer pageSize, Integer pageNum) {
        QueryWrapper<SmsTeachAdministrativeStaffCheckInApplication> queryWrapper = new QueryWrapper<>();
        if (!isNullOrEmpty(apply_unit)) {
            queryWrapper.lambda().like(SmsTeachAdministrativeStaffCheckInApplication::getSmsApplicantName, apply_unit);
        }
        queryWrapper.orderByDesc("create_time");
        Page<SmsTeachAdministrativeStaffCheckInApplication> page = new Page<>(pageNum, pageSize);
        List<SmsTeachAdministrativeStaffCheckInApplicationDTO> collect ;

        Page<SmsTeachAdministrativeStaffCheckInApplication> appApplicationPage = smsTeachAdministrativeStaffCheckInApplicationMapper.selectPage(page, queryWrapper);
        List<SmsTeachAdministrativeStaffCheckInApplication> records = appApplicationPage.getRecords();
        collect = records.stream().map(appApplication -> {
            SmsTeachAdministrativeStaffCheckInApplicationDTO appApplicationResp = new SmsTeachAdministrativeStaffCheckInApplicationDTO();
            BeanUtils.copyProperties(appApplication, appApplicationResp);
            SmsUser smsUser = cacheUtil.getUserInfo(appApplicationResp.getUserId());
            if (smsUser != null) {
                SmsTeachAdministrativeStaffUserDTO user = new SmsTeachAdministrativeStaffUserDTO();
                BeanUtils.copyProperties(smsUser, user);
                appApplicationResp.setApplyUserInfo(user);
            }

            return appApplicationResp;
        }).collect(Collectors.toList());

        int total = (int) page.getTotal();
        return CommonResult.success(collect, total);
    }

    @Override
    @Async
    public Future<ResponseResult> exportTeachApplication(SmsTeachApplicationExportVO exportVO, HttpServletResponse response) {
        if (isNullOrEmpty(exportVO.getIsExportProcess())) {
            return new AsyncResult<>(CommonResult.failed(CommonCodeEnum.INVALID_PARAM));
        }
        try {
            QueryWrapper<SmsTeachAdministrativeStaffCheckInApplication> queryWrapper = new QueryWrapper<>();

            if (!isNullOrEmpty(exportVO.getSmsApplicantName())) {
                queryWrapper.lambda().like(SmsTeachAdministrativeStaffCheckInApplication::getSmsApplicantName, exportVO.getSmsApplicantName());
            }



            queryWrapper.lambda().orderByDesc(SmsTeachAdministrativeStaffCheckInApplication::getCreateTime);
            List<SmsTeachAdministrativeStaffCheckInApplication> list = smsTeachAdministrativeStaffCheckInApplicationMapper.selectList(queryWrapper);
            //表头数据
            String[] header = exportVO.getLimitColumn().toArray(new String[0]);
            double sheetNum;
            //声明一个工作簿
            HSSFWorkbook workbook = new HSSFWorkbook();
            if (list != null && list.size() > 0) {
                sheetNum = Math.ceil((double) list.size() / PER_SHEET_NUM);
                for (int k = 0; k < sheetNum; k++) {
                    //生成一个表格，设置表格名称为"资源导出表"
                    HSSFSheet sheet = workbook.createSheet("教职工入住申请记录导出表" + (k + 1));

                    //设置表格列宽度为10个字节
                    sheet.setDefaultColumnWidth(12);
                    //创建标题的显示样式
                    HSSFCellStyle headerStyle = workbook.createCellStyle();
                    headerStyle.setFillForegroundColor(IndexedColors.YELLOW.index);
                    headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);

                    HSSFFont f = workbook.createFont();
                    f.setFontHeightInPoints((short) 10);//字号
                    f.setBold(true);//加粗
                    headerStyle.setFont(f);
                    //创建第一行表头
                    HSSFRow headrow = sheet.createRow(0);

                    //遍历添加表头(下面模拟遍历学生，也是同样的操作过程)
                    for (int i = 0; i < header.length + 1; i++) {
                        //创建一个单元格
                        HSSFCell cell = headrow.createCell(i);

                        if (i == 0) {
                            //创建一个内容对象
                            HSSFRichTextString text = new HSSFRichTextString("序号");
                            //将内容对象的文字内容写入到单元格中
                            cell.setCellValue(text);
                            cell.setCellStyle(headerStyle);
                            continue;
                        }
                        //创建一个内容对象
                        String header1 = apiModelUtil.getFieldValueByFieldName(SmsTeachAdministrativeStaffCheckInApplication.class, header[i - 1]);
                        HSSFRichTextString text = new HSSFRichTextString(header1);

                        //将内容对象的文字内容写入到单元格中
                        cell.setCellValue(text);
                        cell.setCellStyle(headerStyle);
                    }

                    //判断是否需要添加流程表头
                    if (exportVO.getIsExportProcess() == EXPORT_PROCESS_TRUE) {
                        List<SmsTeachAdministrativeStaffCheckInApplicationProcess> processList =
                                smsTeachAdministrativeStaffCheckInApplicationProcessMapper.selectList(new QueryWrapper<>());
                        if (processList != null && processList.size() > 0) {
                            Integer origin_num = header.length + 1;
                            for (SmsTeachAdministrativeStaffCheckInApplicationProcess process : processList) {
                                String process_name = process.getProcessName();
                                addProcessTableHead(headrow, headerStyle, origin_num, process_name);
                                origin_num += 4;
                            }
                        }
                    }

                    int range = PER_SHEET_NUM;
                    if (k + 1 == sheetNum) {
                        range = list.size() - (PER_SHEET_NUM) * k;
                    }
                    for (int i = 0; i < range; i++) {
                        //创建一行
                        HSSFRow row1 = sheet.createRow(i + 1);
                        SmsTeachAdministrativeStaffCheckInApplication checkInApplication = list.get((PER_SHEET_NUM) * k + i);
                        Map map = JSONObject.parseObject(JSON.toJSONString(checkInApplication), Map.class);
                        row1.createCell(0).setCellValue(new HSSFRichTextString(i + 1 + ""));
                        for (int j = 0; j < header.length; j++) {
                            String rowContent = "";
                            if (map.get(header[j]) instanceof Long) {
                                rowContent = TimeUtil.DateformatTimestamp((long) map.get(header[j]));
                            } else if(map.get(header[j]) instanceof Integer) {
                                rowContent = String.valueOf(map.get(header[j]));
                            }else {
                                if (header[j].equals("userId")) {
                                    SmsUser smsUser = cacheUtil.getUserInfo(checkInApplication.getUserId());
                                    if (smsUser != null) {
                                        rowContent = smsUser.getRealName();
                                    } else {
                                        rowContent = "";
                                    }
                                } else {
                                    rowContent = (String) map.get(header[j]);
                                }
                            }
                            row1.createCell(j + 1).setCellValue(new HSSFRichTextString(rowContent));
                        }

                        if (exportVO.getIsExportProcess() == EXPORT_PROCESS_TRUE) {
                            List<SmsTeachAdministrativeStaffCheckInApplicationProcess> processList =
                                    smsTeachAdministrativeStaffCheckInApplicationProcessMapper.selectList(new QueryWrapper<>());
                            if (processList != null && processList.size() > 0) {
                                Integer origin_num = header.length + 1;
                                for (SmsTeachAdministrativeStaffCheckInApplicationProcess process : processList) {
                                    SmsTeachAdministrativeStaffCheckInApplicationDetail detail =
                                            smsTeachAdministrativeStaffCheckInApplicationDetailMapper.selectOne(new QueryWrapper<SmsTeachAdministrativeStaffCheckInApplicationDetail>()
                                                    .lambda()
                                                    .eq(SmsTeachAdministrativeStaffCheckInApplicationDetail::getApplicationId, checkInApplication.getId())
                                                    .eq(SmsTeachAdministrativeStaffCheckInApplicationDetail::getProcessId, process.getId()));
                                    if (detail == null || detail.getId() == null) {
                                        origin_num += 4;
                                    } else {
                                        //审批人
                                        SmsUser user = cacheUtil.getUserInfo(detail.getCheckId());
                                        if (user == null) {
                                            row1.createCell(origin_num++).setCellValue(new HSSFRichTextString(""));
                                        } else {
                                            row1.createCell(origin_num++).setCellValue(new HSSFRichTextString(user.getRealName()));
                                        }

                                        //审批时间
                                        Date allow_time = detail.getProcessTime();
                                        if (allow_time == null) {
                                            row1.createCell(origin_num++).setCellValue(new HSSFRichTextString(""));
                                        } else {
                                            row1.createCell(origin_num++).setCellValue(new HSSFRichTextString(TimeUtil.DateHanZiSimpleFormat(allow_time)));
                                        }

                                        //审批状态
                                        Integer allow_status = detail.getDetailAllowStatus();
                                        if (allow_status == EXAMINE_STATUS_PASS) {
                                            row1.createCell(origin_num++).setCellValue(new HSSFRichTextString("同意"));
                                        } else if (allow_status == EXAMINE_STATUS_DENY) {
                                            row1.createCell(origin_num++).setCellValue(new HSSFRichTextString("拒绝"));
                                        } else {
                                            row1.createCell(origin_num++).setCellValue(new HSSFRichTextString(""));
                                        }

                                        //审批意见
                                        String allow_option = detail.getDetailAllowOption();
                                        if (isNullOrEmpty(allow_option)) {
                                            row1.createCell(origin_num++).setCellValue(new HSSFRichTextString(""));
                                        } else {
                                            row1.createCell(origin_num++).setCellValue(new HSSFRichTextString(allow_option));
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }

//            response.reset();
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("教职工入住记录导出表.xlsx", "utf-8"));
            response.setCharacterEncoding("utf-8");
            response.setHeader("file-type", "download");
            response.setHeader("file-name", URLEncoder.encode("教职工入住记录导出表.xlsx", "utf-8"));
            response.setHeader("Access-Control-Expose-Headers", "file-type,file-name");
//            //刷新缓冲
            response.flushBuffer();
            //workbook将Excel写入到response的输出流中，供页面下载
            OutputStream os = response.getOutputStream();
            workbook.write(os);

            workbook.close();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
            return new AsyncResult<>(CommonResult.failed(CommonCodeEnum.FAIL));
        }
        return null;
    }
    private void addProcessTableHead(HSSFRow headRow, HSSFCellStyle headerStyle, Integer origin_cell_num, String originHeadContent) {
        Integer cell_num = origin_cell_num;

        setTableHead(headRow, headerStyle, cell_num++, originHeadContent + "审批人");
        setTableHead(headRow, headerStyle, cell_num++, originHeadContent + "审批时间");
        setTableHead(headRow, headerStyle, cell_num++, originHeadContent + "审批状态");
        setTableHead(headRow, headerStyle, cell_num, originHeadContent + "审批意见");

    }
    private void setTableHead(HSSFRow headRow, HSSFCellStyle headerStyle, Integer cell_num, String headContent) {
        HSSFCell cell = headRow.createCell(cell_num);
        //创建一个内容对象
        HSSFRichTextString text = new HSSFRichTextString(headContent);

        //将内容对象的文字内容写入到单元格中
        cell.setCellValue(text);
        cell.setCellStyle(headerStyle);
    }
}
